package com.heima.behavior.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.consatnts.article.HotArticleConstants;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.app.NewBehaviorDTO;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * author by itheima
 *
 * @Date 2022/3/8
 * Description
 */
@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    /**
     * 记录阅读行为
     *
     * @param dto
     * @return
     */
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
        //  1. 校验参数 文章id必须传
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章id不存在");
        }
        //   2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        ApUser user = AppThreadLocalUtils.getUser();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(user.getId(), dto.getEquipmentId());
        // 3. 判断阅读行为是否存在
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(apBehaviorEntry.getId()));

        ApReadBehavior apRead = mongoTemplate.findOne(query, ApReadBehavior.class);
        if (apRead == null) {
            //  5. 不存在  创建阅读行为 并初始化count字段值为 1
            ApReadBehavior apReadBehavior = new ApReadBehavior();
            apReadBehavior.setCount((short) 1);
            apReadBehavior.setArticleId(dto.getArticleId());
            apReadBehavior.setEntryId(apBehaviorEntry.getId());
            apReadBehavior.setReadDuration(dto.getReadDuration());
            apReadBehavior.setPercentage(dto.getPercentage());
            apReadBehavior.setLoadDuration(dto.getLoadDuration());
            mongoTemplate.save(apReadBehavior);
        } else {
            // 4. 存在  将阅读行为的count字段加1 并修改
            Update update = new Update();
            update.set("count", apRead.getCount() + 1);
            mongoTemplate.updateMulti(query, update, ApReadBehavior.class);
        }
        //阅读行为  发送消息
        NewBehaviorDTO behaviorDTO = new NewBehaviorDTO();
        behaviorDTO.setType(NewBehaviorDTO.BehaviorType.VIEWS);
        behaviorDTO.setArticleId(dto.getArticleId());
        behaviorDTO.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(behaviorDTO));
        log.info("成功发送  阅读行为消息 ==》{}",behaviorDTO);
        return ResponseResult.okResult();
    }
}
